<?php

namespace process;

use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Chunk;
use Workerman\Protocols\Http\Response;
use GuzzleHttp\Client;

class ChatGpt
{
    public function onMessage(TcpConnection $connection, Request $request)
    {
        $response = new Response(
            200,
            ['Transfer-Encoding' => 'chunked'],
            "\r\n"
        );
        // 给响应添加跨域相关的http头
        $response->withHeaders([
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Allow-Origin' => $request->header('origin', '*'),
            'Access-Control-Allow-Methods' => $request->header('access-control-request-method', '*'),
            'Access-Control-Allow-Headers' => $request->header('access-control-request-headers', '*'),
        ]);
        $connection->send($response);
        if ($request->method() === "POST") {
            $param = $request->post();

            $client = new Client();
            $api = $client->request(
                'POST',
                'http://you.gpt.com/',
                [
                    'stream' => true, //请求数据流
                    "json" => [
                        "messages" => json_encode($param["msg"], 320)
                    ],
                    'progress' => function ($bytesTransferred, $size) use (&$fileSize) {
                        $fileSize = $size; // 更新已传输的总字节数
                    }
                ]
            );

            $api = $api->getBody();

            $i = $fileSize;
            $str = "";
            while (!$api->eof()) {
                $str .= $api->read(1);
                if ($i != $fileSize && $i > 200) {
                    $arr = GptData($str);
                    foreach ($arr as $k => $v) {
                        // $connection->send(new Chunk(json_encode($v, 320)));
                        // usleep(10000);
                        $connection->send(new Chunk($v));
                    }
                    $str = "";
                }
                $i = $fileSize;
            }
            $connection->send(new Chunk(''));
            return;
        }
        $connection->send(new Chunk(''));
        return;
        /* $timer_id = Timer::add(2, function () use ($connection, &$timer_id, $total_count) {
            static $count = 0;
            // 连接关闭的时候要将定时器删除，避免定时器不断累积导致内存泄漏
            if ($connection->getStatus() !== TcpConnection::STATUS_ESTABLISHED) {
                Timer::del($timer_id);
                return;
            }
            if ($count++ >= $total_count) {
                // 发送一个空的''代表结束响应
                $connection->send(new Chunk(''));
                return;
            }
            // 发送chunk数据
            $connection->send(new Chunk("第{$count}段数据<br>"));
        }); */
    }
}
